﻿package base.helper;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;

public class BaseHelper
{
	/**
	 * MD5加密
	 * 
	 * @param s
	 *            被加密的字符串
	 * @return 加密后的字符串
	 */
	public static String md5(String s)
	{
		if (s == null) s = "";
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try
		{
			byte[] strTemp = s.getBytes();
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++)
			{
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 按字节截取字符串
	 * 
	 * @param str
	 *            被截取的字符串
	 * @param length
	 *            保留的长度
	 * @return 截取后的字符串
	 */
	public static String subString(String str, int length)
	{
		return subString(str, length, "");
	}

	/**
	 * 按字节截取字符串
	 * 
	 * @param str
	 *            被截取的字符串
	 * @param length
	 *            保留的长度
	 * @param fill
	 *            如果被截取, 填充的字符串
	 * @return 截取后的字符串
	 */
	public static String subString(String str, int length, String fill)
	{
		if (length < 0) length = 0;

		int nowLength = 0;
		String returnStr = "";
		char[] tempCharArray = str.toCharArray();
		for (char tempChar : tempCharArray)
		{
			if (nowLength >= length)
			{
				if (!StringUtils.isEmpty(fill)) returnStr += fill;
				break;
			}
			int size = String.valueOf(tempChar).getBytes().length;
			nowLength += size;
			returnStr += tempChar;
		}

		return returnStr;
	}

	/**
	 * 获得类泛型第一个参数的Class
	 * 
	 * @param clazz
	 * @return
	 */
	public static Class getSuperClassGenricType(Class clazz)
	{
		return getSuperClassGenricType(clazz, 0);
	}

	/**
	 * 获得类泛型参数的Class
	 * 
	 * @param clazz
	 * @param index
	 *            第几个参数, 从0开始
	 * @return
	 */
	public static Class getSuperClassGenricType(Class clazz, int index)
	{

		Type genType = clazz.getGenericSuperclass();

		if (!(genType instanceof ParameterizedType))
		{
			return Object.class;
		}

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		if (index >= params.length || index < 0)
		{
			return Object.class;
		}
		if (!(params[index] instanceof Class))
		{
			return Object.class;
		}
		return (Class) params[index];
	}

	/**
	 * 生成一个仅包括数字和字母的随机字符串
	 * 
	 * @param count
	 * @return
	 */
	public static String randomString(int count)
	{
		if (count < 0) count = 0;
		return RandomStringUtils.random(count, "abcdefghijklmnopqrstuvwxyz1234567890");
	}

	/**
	 * 获得国际化文件信息
	 * 
	 * @param bundleName
	 *            国际化文件名称
	 * @param fieldName
	 *            信息名称
	 * @return
	 */
	public static String getMessage(String bundleName, String fieldName, Object... arguments)
	{
		ResourceBundle bundle = ResourceBundle.getBundle("message." + bundleName, Locale.CHINA);

		String label = null;
		try
		{
			label = bundle.getString(fieldName);
			if (arguments.length != 0)
			{
				label = MessageFormat.format(label, arguments);
			}
		}
		catch (MissingResourceException e)
		{
			label = "No Find:" + fieldName;
		}

		return label;
	}

	/**
	 * 利用反射获得对象的属性值
	 * 
	 * @param bean
	 *            处理的对象
	 * @param prop
	 *            对象属性
	 * @return 对象的属性（值）
	 */
	public static Object getPropValue(Object bean, String prop)
	{
		Object result = null;
		try
		{
			result = getPropReadMethod(bean.getClass(), prop).invoke(bean);
		}
		catch (Exception e)
		{
			throw new RuntimeException("读取属性值失败!");
		}

		return result;
	}

	/**
	 * 利用反射获取属性的读取方法
	 * 
	 * @param bean
	 *            处理的对象
	 * @param prop
	 *            对象属性
	 * @return 对象属性的读取方法
	 */
	public static Method getPropReadMethod(Class clazz, String prop)
	{
		Method result = null;
		try
		{
			result = getProp(clazz, prop).getReadMethod();
		}
		catch (Exception e)
		{
			throw new RuntimeException("获取属性的读取方法失败!");
		}

		return result;
	}

	/**
	 * 利用反射获取属性对象
	 * 
	 * @param clazz
	 *            处理的对象
	 * @param prop
	 *            对象属性名称
	 * @return 对象属性
	 */
	public static PropertyDescriptor getProp(Class clazz, String prop)
	{
		PropertyDescriptor result = null;
		try
		{
			BeanInfo binfo = Introspector.getBeanInfo(clazz);
			PropertyDescriptor[] properties = binfo.getPropertyDescriptors();
			if (properties != null)
			{
				for (PropertyDescriptor property : properties)
				{
					if (property.getName().equals(prop))
					{
						result = property;
					}
				}
			}
		}
		catch (Exception e)
		{
			throw new RuntimeException("获取属性失败!");
		}

		return result;
	}

	/**
	 * 获取文件的后缀名
	 * 
	 * @param filePath
	 *            文件路径
	 * @return
	 */
	public static String getSuffix(String filePath)
	{
		// 如果路径中包含/符号，则所有/符号前的内容
		if (filePath.contains("/")) filePath = filePath.substring(filePath.lastIndexOf("/"));
		// 如果文件名中不包括.号，则返回空，否则返回最后一个.号后的字符
		if (!filePath.contains(".")) return "";
		else return filePath.substring(filePath.lastIndexOf(".") + 1);
	}

	/**
	 * 字符串转化为时间类型
	 * @param date
	 * @param patten
	 * @return
	 */
	public static Date parseDate(String date, String patten)
	{
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat(patten);
			Date result = sdf.parse(date);
			return result;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return new Date();
		}
	}
	
	/**
	 * 计算时间戳的间隔 精确到分
	 * @param timeInSeconds
	 * @return
	 */
	public static String canageDHMS(long timeInSeconds)
	{
		long days, hours, minutes, seconds;
		//1(day)*24(hour)*60(minite)*60(seconds)*1000(millisecond)
		days = timeInSeconds / 86400000;
		timeInSeconds = timeInSeconds - (days * 3600 * 24 * 1000);
		//1(hour)*60(minite)*60(seconds)*1000(millisecond)
		hours = timeInSeconds / 3600000;
		timeInSeconds = timeInSeconds - (hours * 3600 * 1000);
		//1(seconds)*1000(millisecond)
		minutes = timeInSeconds / 60000;
		timeInSeconds = timeInSeconds - (minutes * 60 * 1000);
		//1(seconds)*1000(millisecond)
		seconds = timeInSeconds / 1000;
		return days + "天" + hours + "时" + minutes + "分";
	}
	
	public static void main(String[] args)
	{
		System.out.println(BaseHelper.canageDHMS(1000));
	}
}
